package com.example.fence.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Data
public class HttpClientUtil {
    //参数:url:登录认证的api username:用户名 password:密码
    //返回值:[token,refreshToken]
    public static String[] get_token(String url,String username,String password) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        User user = new User(username,password);
        String jsonString = JSON.toJSONString(user);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        String token = null;
        String refreshToken= null;
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            Integer statusCode=response.getStatusLine().getStatusCode();
          //  System.out.println("响应状态为:" + response.getStatusLine());
//            System.out.println("Response"+response);
//            System.out.println("响应结果为:"+EntityUtils.toString(responseEntity));
            if (responseEntity != null) {
                JSONObject body = JSON.parseObject(EntityUtils.toString(responseEntity));
                token = JSONObject.toJSONString(body.get("token"));
               // System.out.println("token:"+token);
                token = token.substring(1,token.length()-1);
                refreshToken = JSONObject.toJSONString(body.get("refreshToken"));
                refreshToken = refreshToken.substring(1,refreshToken.length()-1);
                return new String[] {token,refreshToken};
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                token = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String[] {token,refreshToken};
    }
    //参数:url:刷新token的api refreshToken:refreshToken
    //返回值:[token,refreshToken]
    public static String[] get_token_refresh(String url,String refreshToken) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        Auth refreshTokenoObj = new Auth(refreshToken);
        String jsonString = JSON.toJSONString(refreshTokenoObj);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        String token = null;
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                JSONObject body = JSON.parseObject(EntityUtils.toString(responseEntity));
                token = JSONObject.toJSONString(body.get("token"));
                token = token.substring(1,token.length()-1);
                refreshToken = JSONObject.toJSONString(body.get("refreshToken"));
                refreshToken = refreshToken.substring(1,refreshToken.length()-1);
                //System.out.println("arrive");
//                System.out.println(token);
                return new String[] {token,refreshToken};
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                token = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String[] {token,refreshToken};
    }
    //参数:url:查询数据api token:token
    //返回值:[statusCode, json格式数据]
    public static String[] get_data(String url,String token) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=utf8");
        httpGet.setHeader("token", token);
        token = "Bearer " + token;
        httpGet.setHeader("Authorization", token);
        //System.out.println(token);
        // 响应模型
        CloseableHttpResponse response = null;
        String data = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            Integer statusCode=response.getStatusLine().getStatusCode();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                data = EntityUtils.toString(responseEntity);
                //JSONObject body = JSON.parseObject(EntityUtils.toString(responseEntity));
                //token = JSONObject.toJSONString(body.get("token"));
                return new String[]{statusCode.toString(),data};
//                return data;
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                data = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
//        return data;
    }

    public static String[] post_data(String url,Object jsonObj,String token){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        String jsonString = JSON.toJSONString(jsonObj);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("token", token);
        token = "Bearer " + token;
        httpPost.setHeader("Authorization", token);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        String data = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println("响应状态为:" + response.getStatusLine());
//            System.out.println("Response"+response);
//            System.out.println("响应结果为:"+EntityUtils.toString(responseEntity));
            if (responseEntity != null) {
                data = EntityUtils.toString(responseEntity);
                return new String[]{Integer.toString(statusCode),data};
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                token = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取Token的原始json形式
     * @param url
     * @param username
     * @param password
     * @return [statusCode,jsonData]
     */
    public static String[] get_token_json(String url,String username,String password) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        User user = new User(username,password);
        String jsonString = JSON.toJSONString(user);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        String token = null;
        String refreshToken= null;
        // 响应模型
        CloseableHttpResponse response = null;
        String data=null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);;
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            Integer statusCode=response.getStatusLine().getStatusCode();
            System.out.println("响应状态为:" + response.getStatusLine());

            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                data = EntityUtils.toString(responseEntity);
                //JSONObject body = JSON.parseObject(EntityUtils.toString(responseEntity));
                //token = JSONObject.toJSONString(body.get("token"));
                return new String[]{statusCode.toString(),data};
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                data = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取刷新Token的json形式
     * @param url
     * @param refreshToken
     * @return
     */
    public static String[] get_token_refresh_json(String url,String refreshToken) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        Auth refreshTokenoObj = new Auth(refreshToken);
        String jsonString = JSON.toJSONString(refreshTokenoObj);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        String token = null;
        // 响应模型
        CloseableHttpResponse response = null;
        String data=null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            Integer statusCode=response.getStatusLine().getStatusCode();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                data = EntityUtils.toString(responseEntity);
                //JSONObject body = JSON.parseObject(EntityUtils.toString(responseEntity));
                //token = JSONObject.toJSONString(body.get("token"));
                return new String[]{statusCode.toString(),data};
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
                token = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}


class User
{
    public String username;
    public String password;
    User(String username,String password)
    {
        this.username = username;
        this.password = password;
    }
}

class Auth
{
    public String refreshToken;
    Auth(String refreshToken)
    {
        this.refreshToken = refreshToken;
    }
}
